#! /bin/bash

HOSTNAME="walle"
USERNAME="linux"

PACKAGE="vim git zsh wpa_supplicant dhcpcd man base-devel sudo"

show () {
    echo -e "\e[36;1m$*\e[0m"
}

trytodo () {
    show "$1"
    $2
    if [ $? -ne 0 ]
    then
        show "[ failed ]"
        exit 1
    fi
}

ensure () {
    if [ $1 != y ]
    then
        show "user denied"
        exit 1
    fi
}

###########################################################################

set_timezone () {
    ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
    hwclock --systohc
}

set_localization () {
    echo "en_US.UTF-8 UTF-8"    > /etc/locale.gen
    locale-gen
    echo "LANG=en_US.UTF8"      > /etc/locale.conf
}

set_network () {
    echo $HOSTNAME > /etc/hostname

    echo "127.0.0.1     localhost" >  /etc/hosts
    echo "::1           localhost" >> /etc/hosts
    echo "127.0.1.1     $HOSTNAME localdomain $HOSTNAME" >> /etc/hosts
}

set_bootloder () {
    pacman -S grub efibootmgr intel-ucode os-prober
    mkdir /boot/grub
    grub-mkconfig > /boot/grub/grub.cfg
    grub-install --target=x86_64-efi --efi-directory=/boot
}

###########################################################################

show "under new root: [`pwd`], continue [y/n]"
read -p "=> " ANS
ensure $ANS

trytodo "time zone"                 "set_timezone"

trytodo "localization"              "set_localization"

trytodo "network host"              "set_network"

trytodo "initramfs"                 "mkinitcpio -P"

trytodo "password [`whoami`]"       "passwd"

trytodo "bootloader"                "set_bootloder"

trytodo "install packages"          "pacman -S $PACKAGE"

trytodo "network enable"	    "systemctl enable dhcpcd"

trytodo "add user [$USERNAME]" 	    "useradd -m -G wheel $USERNAME"

trytodo "password [$USERNAME]"	    "passwd $USERNAME"

trytodo "edit sudoers..."	    "/edit-sudoers.sh"

show "[ arch chroot finish ]"

exit
